const { ipcRenderer } = require('electron');

// 获取DOM元素
const closeBtn = document.getElementById('close-btn');
const minimizeBtn = document.getElementById('minimize-btn');
const changeStatusBtn = document.getElementById('change-status-btn');
const manageStatusBtn = document.getElementById('manage-status-btn');
const addTaskBtn = document.getElementById('add-task-btn');
const manageTasksBtn = document.getElementById('manage-tasks-btn');
const dailyReportBtn = document.getElementById('daily-report-btn');
const weeklyReportBtn = document.getElementById('weekly-report-btn');
const monthlyReportBtn = document.getElementById('monthly-report-btn');

// 添加分享按钮
const shareBtn = document.createElement('button');
shareBtn.id = 'share-btn';
shareBtn.textContent = '🌐';
shareBtn.title = '局域网分享';
shareBtn.style.cssText = `
    position: absolute;
    top: 10px;
    right: 80px;
    background: #17a2b8;
    color: white;
    border: none;
    width: 25px;
    height: 25px;
    border-radius: 50%;
    cursor: pointer;
    font-size: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
`;

document.querySelector('.widget-header').appendChild(shareBtn);

shareBtn.addEventListener('click', () => {
    ipcRenderer.send('open-share-manager');
});

// 关闭挂件
closeBtn.addEventListener('click', () => {
    ipcRenderer.send('close-widget');
});

// 最小化挂件
minimizeBtn.addEventListener('click', () => {
    ipcRenderer.send('minimize-widget');
});

// 切换工位状态
let statusOptions = [
    { name: '工作中', color: '#28a745' },
    { name: '会议中', color: '#17a2b8' },
    { name: '休息中', color: '#ffc107' },
    { name: '免打扰', color: '#dc3545' }
];
let currentStatusIndex = 0;
const currentStatusElement = document.getElementById('current-status');
let currentStatusName = '工作中';

changeStatusBtn.addEventListener('click', () => {
    currentStatusIndex = (currentStatusIndex + 1) % statusOptions.length;
    const status = statusOptions[currentStatusIndex];
    currentStatusElement.textContent = status.name;
    currentStatusElement.style.backgroundColor = status.color;
    currentStatusName = status.name;
    
    // 通知主进程更新当前状态
    ipcRenderer.send('set-current-status', status);
});

// 更新状态选项函数
function updateStatusOptions(statusManager) {
    // 合并默认状态和自定义状态
    const allStatuses = [...statusManager.default, ...statusManager.custom];
    
    // 更新状态选项数组
    statusOptions = allStatuses.map(status => ({
        name: status.name,
        color: status.color
    }));
    
    // 查找当前状态的索引
    const currentIndex = statusOptions.findIndex(status => status.name === currentStatusName);
    if (currentIndex !== -1) {
        currentStatusIndex = currentIndex;
    } else {
        currentStatusIndex = 0;
    }
}

// 管理工位状态
manageStatusBtn.addEventListener('click', () => {
    ipcRenderer.send('open-status-manager');
});

// 监听状态更新
ipcRenderer.on('update-current-status', (event, status) => {
    currentStatusElement.textContent = status.name;
    currentStatusElement.style.backgroundColor = status.color;
    currentStatusName = status.name;
    
    // 更新当前状态索引
    const currentIndex = statusOptions.findIndex(s => s.name === status.name);
    if (currentIndex !== -1) {
        currentStatusIndex = currentIndex;
    }
});

// 添加任务
addTaskBtn.addEventListener('click', () => {
    ipcRenderer.send('open-task-manager');
});

// 管理任务
manageTasksBtn.addEventListener('click', () => {
    ipcRenderer.send('open-task-manager');
});

// 存储当前激活的过滤器
let activeFilter = 'all';
let allTasks = [];

// 监听任务更新
ipcRenderer.on('tasks-updated', (event, tasks) => {
    allTasks = tasks;
    filterAndRenderTasks();
});

// 监听初始任务数据
ipcRenderer.on('task-data', (event, tasks) => {
    allTasks = tasks;
    filterAndRenderTasks();
});

// 监听状态列表更新
ipcRenderer.on('status-list-updated', (event, statusManager) => {
    // 更新状态切换按钮的选项
    updateStatusOptions(statusManager);
});

// 更新状态选项
function updateStatusOptions(statusManager) {
    // 合并默认状态和自定义状态
    const allStatuses = [...statusManager.default, ...statusManager.custom];
    
    // 更新状态选项数组
    statusOptions = allStatuses.map(status => ({
        name: status.name,
        color: status.color
    }));
    
    // 确保当前索引在有效范围内
    if (currentStatusIndex >= statusOptions.length) {
        currentStatusIndex = 0;
    }
}

// 应用设置到挂件
function applySettings(settings) {
    const widgetContainer = document.querySelector('.widget-container');
    const widgetContent = document.querySelector('.widget-content');
    
    // 应用背景颜色和透明度
    if (settings.backgroundColor) {
        widgetContainer.style.backgroundColor = settings.backgroundColor;
    }
    
    // 应用字体颜色
    if (settings.fontColor) {
        widgetContent.style.color = settings.fontColor;
    }
    
    // 应用字体大小
    if (settings.fontSize) {
        widgetContent.style.fontSize = settings.fontSize + 'px';
    }
    
    // 保存设置到本地存储
    localStorage.setItem('widgetSettings', JSON.stringify(settings));
}

// 过滤并渲染任务列表
function filterAndRenderTasks() {
    let filteredTasks = [];
    
    // 根据当前过滤器筛选任务
    if (activeFilter === 'all') {
        filteredTasks = allTasks;
    } else {
        filteredTasks = allTasks.filter(task => task.status === activeFilter);
    }
    
    renderTasks(filteredTasks);
    
    // 任务渲染完成后，调整窗口大小以适应内容
    adjustWindowSizeToContent();
}

// 根据内容自动调整窗口大小
function adjustWindowSizeToContent() {
    const widgetContainer = document.querySelector('.widget-container');
    const widgetContent = document.querySelector('.widget-content');
    
    if (widgetContainer && widgetContent) {
        // 获取内容实际高度，确保包括所有子元素
        const contentHeight = widgetContent.scrollHeight;
        const currentWidth = widgetContainer.offsetWidth;
        
        // 总是调整窗口大小，而不仅仅是在内容高度大于当前窗口高度时
        // 添加更多的边距以确保所有内容都可见
        const newHeight = contentHeight + 40; // 增加额外的边距到40px，确保底部按钮完全可见
        
        // 发送调整大小消息到主进程
        ipcRenderer.send('resize-widget', { width: Math.round(currentWidth), height: Math.round(newHeight) });
    }
}

// 渲染任务列表
function renderTasks(tasks) {
    const taskList = document.getElementById('task-list');
    taskList.innerHTML = '';
    
    if (!tasks || tasks.length === 0) {
        const emptyTaskItem = document.createElement('li');
        emptyTaskItem.className = 'task-item empty-task';
        emptyTaskItem.textContent = '暂无任务';
        taskList.appendChild(emptyTaskItem);
        return;
    }
    
    // 显示所有任务，支持滚动查看
    tasks.forEach(task => {
        const taskItem = document.createElement('li');
        taskItem.className = `task-item ${task.status === 'completed' ? 'completed' : ''}`;
        
        // 优先级文本
        const priorityText = {
            'low': '低',
            'medium': '中',
            'high': '高'
        };
        
        // 状态文本
        const statusText = {
            'pending': '待办',
            'in-progress': '进行中',
            'completed': '完成'
        };
        
        taskItem.innerHTML = `
            <div class="task-title ${task.status === 'completed' ? 'completed' : ''}">
                ${task.title}
            </div>
            <div class="task-meta">
                <span class="task-priority priority-${task.priority}">
                    ${priorityText[task.priority]}
                </span>
                <span class="task-status-badge status-${task.status}" data-task-id="${task.id}">
                    ${statusText[task.status]}
                </span>
            </div>
        `;
        
        taskList.appendChild(taskItem);
        
        // 为任务状态标签添加点击事件
        const statusBadge = taskItem.querySelector('.task-status-badge');
        if (statusBadge) {
            statusBadge.addEventListener('click', (e) => {
                e.preventDefault();
                e.stopPropagation();
                // 发送切换任务状态的消息到主进程
                ipcRenderer.send('toggle-task-status', parseInt(task.id));
            });
            
            // 添加鼠标样式
            statusBadge.style.cursor = 'pointer';
            statusBadge.style.pointerEvents = 'auto';
        }
    });
}

// 初始化时渲染任务和应用设置
document.addEventListener('DOMContentLoaded', () => {
    // 请求获取今日任务数据
    ipcRenderer.send('get-today-tasks');
    
    // 应用已保存的设置
    const savedSettings = localStorage.getItem('widgetSettings');
    if (savedSettings) {
        const settings = JSON.parse(savedSettings);
        applySettings(settings);
    }
    
    // 添加过滤按钮事件监听器
    const filterBtns = document.querySelectorAll('.filter-btn');
    filterBtns.forEach(btn => {
        btn.addEventListener('click', () => {
            const filter = btn.getAttribute('data-filter');
            if (filter) {
                // 更新激活的过滤器
                activeFilter = filter;
                
                // 更新按钮样式
                filterBtns.forEach(b => b.classList.remove('active'));
                btn.classList.add('active');
                
                // 过滤并重新渲染任务
                filterAndRenderTasks();
            }
        });
    });
    
    // 确保初始加载时窗口大小正确
    setTimeout(() => {
        adjustWindowSizeToContent();
    }, 300);
});

// 监听设置更新
ipcRenderer.on('settings-updated', (event, settings) => {
    applySettings(settings);
});

// 监听窗口大小变化
ipcRenderer.on('widget-resized', (event, { width, height }) => {
    const widgetContainer = document.querySelector('.widget-container');
    if (widgetContainer) {
        widgetContainer.style.width = width + 'px';
        widgetContainer.style.height = height + 'px';
    }
});

// 添加获取今日任务的函数
function getTodayTasks() {
    ipcRenderer.send('get-today-tasks');
}

// 生成报告
dailyReportBtn.addEventListener('click', () => {
    ipcRenderer.send('open-report-generator', 'daily');
});

weeklyReportBtn.addEventListener('click', () => {
    ipcRenderer.send('open-report-generator', 'weekly');
});

monthlyReportBtn.addEventListener('click', () => {
    ipcRenderer.send('open-report-generator', 'monthly');
});

// 实现窗口拖拽功能
const widgetHeader = document.querySelector('.widget-header');
const widgetContainer = document.querySelector('.widget-container');
let isDragging = false;
let isResizing = false;
let currentX;
let currentY;
let initialX;
let initialY;
let xOffset = 0;
let yOffset = 0;
let startX, startY, startWidth, startHeight;

widgetHeader.addEventListener('mousedown', dragStart);
document.addEventListener('mouseup', dragEnd);
document.addEventListener('mousemove', drag);

// 添加调整大小功能
const resizeHandle = document.createElement('div');
resizeHandle.className = 'resize-handle';
resizeHandle.innerHTML = '⋮';
widgetContainer.appendChild(resizeHandle);

resizeHandle.addEventListener('mousedown', startResize);

function dragStart(e) {
    // 只有在点击标题栏时才允许拖拽
    if (e.target === widgetHeader || widgetHeader.contains(e.target)) {
        initialX = e.clientX - xOffset;
        initialY = e.clientY - yOffset;
        
        isDragging = true;
    }
}

function dragEnd(e) {
    initialX = currentX;
    initialY = currentY;
    
    isDragging = false;
    isResizing = false;
}

function drag(e) {
    if (isDragging) {
        e.preventDefault();
        currentX = e.clientX - initialX;
        currentY = e.clientY - initialY;
        
        xOffset = currentX;
        yOffset = currentY;
        
        // 发送移动消息到主进程
        ipcRenderer.send('move-widget', { x: Math.round(currentX), y: Math.round(currentY) });
    }
    
    if (isResizing) {
        e.preventDefault();
        const newWidth = startWidth + (e.clientX - startX);
        const newHeight = startHeight + (e.clientY - startY);
        
        // 确保最小尺寸
        const minWidth = 200;
        const minHeight = 250;
        
        if (newWidth >= minWidth && newHeight >= minHeight) {
            // 发送调整大小消息到主进程
            ipcRenderer.send('resize-widget', { width: Math.round(newWidth), height: Math.round(newHeight) });
            
            // 同时调整内部内容的大小
            const widgetContainer = document.querySelector('.widget-container');
            if (widgetContainer) {
                widgetContainer.style.width = Math.round(newWidth) + 'px';
                widgetContainer.style.height = Math.round(newHeight) + 'px';
            }
        }
    }
}

function startResize(e) {
    isResizing = true;
    startX = e.clientX;
    startY = e.clientY;
    
    const widgetContainer = document.querySelector('.widget-container');
    startWidth = widgetContainer.offsetWidth;
    startHeight = widgetContainer.offsetHeight;
    
    e.preventDefault();
    e.stopPropagation(); // 阻止事件冒泡
}

// 添加创建新挂件按钮和设置按钮
document.addEventListener('DOMContentLoaded', () => {
    // 添加创建新挂件按钮
    const createWidgetBtn = document.createElement('button');
    createWidgetBtn.id = 'create-widget-btn';
    createWidgetBtn.textContent = '新建挂件';
    createWidgetBtn.style.cssText = `
        position: absolute;
        bottom: 60px;
        right: 10px;
        background: #667eea;
        color: white;
        border: none;
        padding: 5px 10px;
        border-radius: 15px;
        cursor: pointer;
        font-size: 12px;
        transition: all 0.3s ease;
    `;

    const widgetContainer = document.querySelector('.widget-container');
    if (widgetContainer) {
        widgetContainer.appendChild(createWidgetBtn);
    }

    createWidgetBtn.addEventListener('click', () => {
        ipcRenderer.send('create-new-widget');
    });

    // 添加设置按钮
    const settingsBtn = document.createElement('button');
    settingsBtn.id = 'settings-btn';
    settingsBtn.textContent = '设置';
    settingsBtn.style.cssText = `
        position: absolute;
        bottom: 30px;
        right: 10px;
        background: #28a745;
        color: white;
        border: none;
        padding: 5px 10px;
        border-radius: 15px;
        cursor: pointer;
        font-size: 12px;
        transition: all 0.3s ease;
    `;

    if (widgetContainer) {
        widgetContainer.appendChild(settingsBtn);
    }

    settingsBtn.addEventListener('click', () => {
        ipcRenderer.send('open-settings');
    });
    
    // 确保按钮在挂件内部可见
    setTimeout(() => {
        if (createWidgetBtn && createWidgetBtn.style) {
            createWidgetBtn.style.position = 'absolute';
        }
        if (settingsBtn && settingsBtn.style) {
            settingsBtn.style.position = 'absolute';
        }
    }, 100);
});